﻿#include "dialogsheetnameselect.h"
#include "ui_dialogsheetnameselect.h"

#include <QCheckBox>
#include<QDebug>
#include <QException>

DialogSheetNameSelect::DialogSheetNameSelect(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::DialogSheetNameSelect)
{
    ui->setupUi(this);
    setFont(QFont("Microsoft Yahei",10));
    setWindowTitle(QString::fromLocal8Bit("协议项选择"));

    connect(ui->comboBox,SIGNAL(currentIndexChanged(int)),this,SLOT(onSelectIndexChange(int)));
}

DialogSheetNameSelect::~DialogSheetNameSelect()
{
    delete ui;
}

void DialogSheetNameSelect::setQxlsxHelper(qxlsxHelper *xlsxhelper)
{
    _qxlsxHelper = xlsxhelper;
    SetSheetName(_qxlsxHelper->GetSheetNames());
}

void DialogSheetNameSelect::SetSheetName(const QStringList &sheetNames)
{
    for (int var = 0; var < sheetNames.size(); ++var) {

        ui->comboBox->addItem(sheetNames[var]);
    }
}

QString DialogSheetNameSelect::GetSheetName()
{
    return _selectSheetName;
}

//获取选中项
QVector<QString> DialogSheetNameSelect::GetCheckItem()
{
    QVector<QString> itemCheckStatus;
    QList<QCheckBox*> all_checkBox = ui->groupBox_checkItem->findChildren<QCheckBox*>();//注意不是gridLayout
    for (auto* checkbox : all_checkBox)
    {
        if(checkbox->isChecked())
        {

            itemCheckStatus.push_back(checkbox->text());
        }
    }
    return itemCheckStatus;
}

void DialogSheetNameSelect::ShowSheetHeaders(const QList<QString>& headers)
{
    try
    {

        QList<QCheckBox*> all_checkBox = ui->groupBox_checkItem->findChildren<QCheckBox*>();//注意不是gridLayout
        for (auto* checkbox : all_checkBox)
        {
            delete checkbox;
        }


        delete ui->groupBox_checkItem->layout();
    }
    catch (QException ex)
    {
        qDebug()<<"excption:"<<ex.what()<<endl;
    }


    QGridLayout* _groupLayout = new QGridLayout();
    for(int i=0;i<headers.count();i++)
    {
        QCheckBox* checkbox = new QCheckBox(headers[i]);
        QString str1=QString::fromLocal8Bit("故障代码");
        QString str2=QString::fromLocal8Bit("车号");
        QString str3=QString::fromLocal8Bit("故障等级");
        QString str4=QString::fromLocal8Bit("信号描述");
        if(headers[i].contains(str1)||headers[i].contains(str2)||headers[i].contains(str3)||headers[i].contains(str4))
        {
            checkbox->setChecked(true);
        }
        else
        {
            checkbox->setChecked(false);

        }
        _groupLayout->addWidget(checkbox);
    }
    ui->groupBox_checkItem->setLayout(_groupLayout);

}

void DialogSheetNameSelect::onSelectIndexChange(int nid)
{
    _selectSheetName= ui->comboBox->currentText();
    _qxlsxHelper->SetCurrentSheetName(_selectSheetName);
    QList<QString> headers;
    _qxlsxHelper->ReadHeader(headers);
    ShowSheetHeaders(headers);

    qDebug()<<"rc headers:"<<headers<<endl;
    qDebug()<<"rc sheetname:"<<_selectSheetName<<endl;
}
